/*
 * display.c
 *
 * This has all the functionality required to display and play Retro Warfare
 *
 *  Created on: Dec 9, 2011
 *      Author: Jonathan Marokhovsky
 */

#include "display.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>

#ifndef BOARD_HEIGHT
#define BOARD_HEIGHT	16
#endif

int boardHeight = BOARD_HEIGHT;

WINDOW *newWin(void)
{
	WINDOW *ret;

	initscr();
	ret = newwin(0,0,0,0);
	curs_set(0);
	leaveok(ret, TRUE);
	signal(SIGINT, cleanUp);
	return ret;
}

int displayWin(WINDOW *win, char *newScreen[boardHeight])
{
	int i, j, tempLen;
	for (i = 0; i < BOARD_HEIGHT; i++)
	{
		tempLen = strlen(newScreen[i]);
		char temp[tempLen];
		strncpy(temp, newScreen[i], tempLen + 1);
		for (j = 0; j < tempLen; j++)
		{
			mvwaddch(win, i, j, temp[j]); // remember, it's (y,x)
		}
	}
	wrefresh(win);
	return 0; // indicate that it closed correctly
}

void cleanUp(int signal)
{
	endwin();
	exit(0);
}

int getMoves(WINDOW *win)
{
	int bytesRecv;
	int tempX = 23, tempY = 8;
	int adder = 14;
	char input;
	fd_set readSet;
	struct timeval timeout;
	timeout.tv_sec = IDLE_TIME;
	timeout.tv_usec = 0;

	FD_ZERO(&readSet);
	FD_SET(0, &readSet);
	nodelay(win, TRUE);
	cbreak();
	noecho();
	while (1)
	{
		bytesRecv = select(1, &readSet, NULL, NULL, &timeout);
		if (bytesRecv == 0)
		{
			mvwaddch(win, tempY, 4 + adder, 'E');
			mvwaddch(win, tempY, 5 + adder, 'x');
			mvwaddch(win, tempY, 6 + adder, 'i');
			mvwaddch(win, tempY, 7 + adder, 't');
			mvwaddch(win, tempY, 8 + adder, 'i');
			mvwaddch(win, tempY, 9 + adder, 'n');
			mvwaddch(win, tempY, 10 + adder, 'g');
			mvwaddch(win, tempY, 11 + adder, '.');
			mvwaddch(win, tempY, 12 + adder, '.');
			mvwaddch(win, tempY, 13 + adder, '.');
			wrefresh(win);
			sleep(1);
			cleanUp(0);
		}
		else if (bytesRecv > 0)
		{
			if (FD_ISSET(0, &readSet))
			{
				input = wgetch(win);
				if (interpretMove(input) == 0)
				{
					// This is a movement, send it
					sendCmd(input);
				}
				else
				{
					if (interpretShot(input) == 0)
					{
						// This is a shot
						// fix it up so it's easier for the server to figure out
						// send it
					}
				}
				mvwaddch(win, tempY, tempX, input);
				wrefresh(win);
				timeout.tv_sec = IDLE_TIME; // reset the input timer
			}
		}
		else
		{
			perror("move getting");
			cleanUp(1);
		}
	}
	return 0;
}

int interpretMove(char cmd)
{
	int ret = 0;
	switch (cmd)
	{
		case 'w':
		case 'W':
		case 'a':
		case 'A':
		case 's':
		case 'S':
		case 'd':
		case 'D':
			break;
		default:
			ret++;
			break;
	}
	return ret;
}

int interpretShot(char cmd)
{
	int ret = 0;
	return ret;
}

int sendCmd(char cmd)
{
	int ret = 0;
	char *message;
	sprintf(message, "%c", cmd);
	strcpy(theMessage, message);
	return ret;
}

char *recvCmd(char *message)
{
	char *ret;
	/* parse the message and make it the return */
	/* set up the socket */
	/* get the message */
	ret = message;
	return ret;
}

